import { onMounted, onUnmounted, Ref, ref } from 'vue'

const useClickOutSide = (refItem: Ref<null | HTMLElement>) => {
  const showMenu = ref(false)
  const handler = (e: MouseEvent) => {
    if (refItem.value) {
      // 当前点击的元素不再指定的元素之中时，关闭菜单
      if (!refItem.value.contains(e.target as HTMLElement)) {
        showMenu.value = false
      } else {
        showMenu.value = !showMenu.value
      }
    }
  }
  onMounted(() => {
    document.addEventListener('click', handler)
  })
  onUnmounted(() => {
    document.removeEventListener('click', handler)
  })
  return showMenu
}

export default useClickOutSide
